<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\controller;

/**
 * Description of Login
 *
 * @author Administrator
 */
use app\BaseController;
use think\captcha\facade\Captcha;
use app\Request;
use think\facade\Db;

class Login extends BaseController {

    //验证码
    public function verify() {

        return Captcha::create();
    }

    //put your code here
    public function index() {
        return view("index", [
            "title" => "登录"
        ]);
    }

    public function loginUp(Request $request) {

        $resData = [];
        $data['admin_name'] = $request->param("admin_name");
        $data['password'] = $request->param("password");

        if (!captcha_check($request->param("code"))) {
            $resData['code'] = 1;
            $resData['msg'] = "验证码错误";
            return $resData; // 验证失败
        }
        $admin = Db::name('admin')->where('admin_name', $data['admin_name'])->findOrEmpty();
      
            if ($admin) {
                if ($admin['password'] == $data['password']) {
                    //保存session
                    session('id', $admin['id']);
                    session('username', $admin['admin_name']);
                    $resData['code']= 3; //登录成功
                    $resData['msg'] = "登录成功";
                } else {
                    $resData['code']= 4; //登录成功
                    $resData['msg'] = "密码错误";
                }
            } else {
                $resData['code'] = 2;
                $resData['msg'] = "账号不存在";
            }
            
            return $resData;
    }

    public function logout() {
        session(null);
        return redirect( '/Login');
    }

}
